import React from 'react';
import { Form } from 'antd';
import items from './items';
import { FormItem } from './types';
import { FormProps, FormInstance } from 'antd/lib/form';

type Props = {
  children?: any;
  onSubmit?(e: any): any;
  formList: FormItem[];
  layout?: FormProps['layout'];
  initialValues?: FormProps['initialValues'];
}

const FormPro = (props: Props, ref: any) => {
  const {
    onSubmit,
    formList,
    children,
    initialValues,
    layout = 'vertical',
  } = props;
  return (
    <Form
      ref={ref}
      layout={layout}
      onFinish={onSubmit}
      initialValues={initialValues}
    >
      {formList.map(((item: FormItem) => {
        const {
          name,
          rules,
          label,
          render,
          labelCol,
          type = 'input',
          initialValue,
        } = item;
        return (
          <Form.Item
            key={name}
            name={name}
            rules={rules}
            label={label}
            initialValue={initialValue}
            children={render?.(item) || items[type]?.(item)}
            labelCol={labelCol ? { span: labelCol } : undefined}
          />
        )
      }))}
      {children}
    </Form>
  )
}

export default React.forwardRef<FormInstance, Props>(FormPro);
